package com.yuji.aacar.pay.acvitity;

import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.view.View;
import android.widget.CompoundButton;
import android.widget.RadioButton;
import android.widget.TextView;
import android.widget.Toast;

import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;
import com.yuji.aacar.R;
import com.yuji.aacar.base.BaseActivity;
import com.yuji.aacar.widgets.dialogue.CheckToast;
import com.yuji.aacar.widgets.dialogue.MyDialog;


/**
 * Title: PayTwoActivity
 * Package:common.com.ttpc.consumer.commonsdk
 * Description: 支付activity
 * Copyright:ttpc All Rights Reserved
 * Author: shengshujie@126.com
 * version: V1.0
 * Date: 2017-01-10
 */
public class PayTwoActivity extends BaseActivity implements View.OnClickListener, CompoundButton.OnCheckedChangeListener {
    private RadioButton mPayRadioButton;
    private RadioButton mWeiXinPayRadioButton;
    private TextView mBack;
    private TextView PayButton;
    private String mOrderInfo;
    private int PayType = 0;//支付的类型 1：微信 2:支付宝 3：银联
    private final int ACTION_WX_PAY = 200;
    private Bundle bundle;
    private int dealerId;//经销商ID
    private int auctionId = 0;//车源ID
    private int paymoney;//单位为分
    private int businessType;//1维保 2保证金
    private String actualIp;//用户终端IP 这里只是例子 接入时传真实的用户终端IP
    public static final int WEIXIN_CODE = 2;
    public static final int ALIPYA_CODE = 1;
//    public static final int UINON_CODE = 3;
    private Integer orderID;
    private ProgressDialog mLoadingDialog = null;
    private static ProgressDialog mPayDialog = null;
    private IWXAPI api = null;
    private WeXinReceiver weXinReceiver;
    public static String WEIXIN_ACITON = "intent_action_pay_ok";
    public static String WEIXIN_ACITON_FAILED = "intent_action_pay_failed";

    private class WeXinReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            if (mPayDialog.isShowing()){
                mPayDialog.dismiss();
            }
            if (intent.getAction().equals(WEIXIN_ACITON)) {
//                CommonDaoImpl.callBack.PaySuccess(UserBean.getInstance());
                finish();
            } else if (intent.getAction().equals(WEIXIN_ACITON_FAILED)) {
                CheckToast.showToast(PayTwoActivity.this,"微信支付失败",Toast.LENGTH_SHORT);
            }
        }
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_pay);
        bundle = getIntent().getBundleExtra("pay");//todo
        dealerId = bundle.getInt("dealerId");
        auctionId = bundle.getInt("auctionId", 0);
        paymoney = bundle.getInt("paymoney");
        businessType = bundle.getInt("businessType");
//        actualIp = Tools.getHostIP();
        mPayRadioButton = (RadioButton) findViewById(R.id.radioButton_zhifubao);
        mPayRadioButton.setOnCheckedChangeListener(this);
        mWeiXinPayRadioButton = (RadioButton) findViewById(R.id.radioButton_weixin);
        mWeiXinPayRadioButton.setOnCheckedChangeListener(this);
        mBack = (TextView) findViewById(R.id.iv_left);
        mBack.setOnClickListener(this);
        PayButton = (TextView) findViewById(R.id.pay_btn);
        PayButton.setOnClickListener(this);
        mLoadingDialog = ProgressDialog.show(this, "", "正在生成订单中,请稍候...", true);
        api = WXAPIFactory.createWXAPI(this, null);

//        TtpApi.getOrderInfo(this, dealerId, auctionId, paymoney, businessType, actualIp, new HttpOnNextListener() {
//            @Override
//            public void onNext(Object o) {
//                if (mLoadingDialog.isShowing()) {
//                    mLoadingDialog.dismiss();
//                }
//                orderID = ((GoodsResult) o).getOrderId();
//                bundle.putInt("orderid", orderID);
//                CheckToast.showToast(PayTwoActivity.this, "生成订单成功", Toast.LENGTH_SHORT);
//
//            }
//        }, new HttpOnErrorListener() {
//            @Override
//            public void onError(Throwable throwable) {
//                if (mLoadingDialog.isShowing()) {
//                    mLoadingDialog.dismiss();
//                }
//                CheckToast.showToast(PayTwoActivity.this, "生成订单失败", Toast.LENGTH_SHORT);
//                finish();
//            }
//        });

        weXinReceiver = new WeXinReceiver();
        IntentFilter filter = new IntentFilter(WEIXIN_ACITON);
        registerReceiver(weXinReceiver, filter);
        mWeiXinPayRadioButton.setChecked(true);
    }

    @Override
    public void onClick(View view) {
        if (view.getId() == R.id.pay_btn) {
            mPayDialog = ProgressDialog.show(PayTwoActivity.this,"","提交订单中，请稍候...",true);
            if (PayType == 0) {
                CheckToast.showToast(this, "请选择支付类型", Toast.LENGTH_SHORT);
            }
            if (PayType == 1) {
                if (!api.isWXAppInstalled()) {
                    CheckToast.showToast(this, "尚未安装微信", Toast.LENGTH_SHORT);
                    if(mPayDialog.isShowing()) {
                        mPayDialog.dismiss();
                    }
                } else {
//                    PayManager mWxPayManager = new WxPayManager(this);
//                    mWxPayManager.excute(actualIp, PayTwoActivity.WEIXIN_CODE, orderID, paymoney, auctionId, businessType);
                }
            }
            if (PayType == 2) {
//                PayManager aliPayManager = new AliPayManager(this);
//                aliPayManager.excute(actualIp, ALIPYA_CODE, orderID, paymoney, auctionId, businessType);
            }
//            if (PayType == 3) {
//                PayManager uinonManager = new UinonManager(this);
//                uinonManager.excute(actualIp, UINON_CODE, orderID, paymoney, auctionId, businessType);
//            }

        } else if (view.getId() == R.id.iv_left) {
            back();
        }
    }

    public static ProgressDialog getDialog () {
        return mPayDialog;
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (mPayDialog.isShowing()){
            mPayDialog.dismiss();
        }
        if (data == null) {
            return;
        }
        if (requestCode == 10) {
            String msg = "";
        /*
         * 支付控件返回字符串:success、fail、cancel 分别代表支付成功，支付失败，支付取消
         */
            String str = data.getExtras().getString("pay_result");
            if (str.equalsIgnoreCase("success")) {
//                CommonDaoImpl.callBack.PaySuccess(UserBean.getInstance());
//                finish();
//            } else if (str.equalsIgnoreCase("fail")) {
//                CommonDaoImpl.callBack.PayFailed("");
//            } else if (str.equalsIgnoreCase("cancel")) {
//                CommonDaoImpl.callBack.PayFailed("");
            }
        }
    }


    @Override
    public void onCheckedChanged(CompoundButton compoundButton, boolean check) {
        if (compoundButton.getId() == R.id.radioButton_weixin) {
            if (check) {
                mPayRadioButton.setChecked(false);
                PayType = 1;
            }
//        } else if (compoundButton.getId() == R.id.radioButton_alipay) {
//            if (check) {
//                mWeiXinPayRadioButton.setChecked(false);
//                PayType = 2;
//            }
//        } else if (compoundButton.getId() == R.id.radioButton_uinon) {
//            if (check) {
//                mPayRadioButton.setChecked(false);
//                mWeiXinPayRadioButton.setChecked(false);
//                PayType = 3;
//            }
        }
    }

    @Override
    public void onBackPressed() {
        back();
    }

    private void back() {
        MyDialog dialog = new MyDialog(this);
        dialog.createDialog("是否取消支付?", "确定", new MyDialog.MyOnclickListener() {
            @Override
            public void onClick(Dialog dialog) {
                finish();
            }
        });
       /* new AlertDialog.Builder(PayTwoActivity.this)
                .setTitle("系统提示")
                .setMessage("是否取消支付?")
                .setPositiveButton("确定", new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        finish();
                    }
                })
                .setNegativeButton("取消", new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {

                    }
                }).create().show();*/
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterReceiver(weXinReceiver);
        PayType = 0;
    }
}
